var base = 'http://www.ipp12349.cn/';
//var base = 'http://qiujin.tunnel.qydev.com/';

Date.prototype.format = function(fmt) {
     var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
     for(var k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
         }
     }
    return fmt;
}

function openBrowse(url, title, share, name, id) {
    api.openWin({
        name: 'browse_' + name,
        url: api.wgtRootDir + '/html/browser.html',
        reload: true,
        pageParam: {
            url: url,
            title: title,
            share: share,
            id: id
        }
    });
}

function domEvtClick(el) {
    var listDom = $api.domAll(el);
    for (var i in listDom) {
        if ($api.attr(listDom[i], 'data-url')) {
            $api.addEvt(listDom[i], 'click', function() {
                var data_url = $api.attr(this, 'data-url');
                var data_title = $api.attr(this, 'data-title');
                var share = true;
                if (data_url.indexOf('http://') < 0) {
                    data_url = api.wgtRootDir + '/html/' + data_url + '.html';
                    share = false;

                    if ($api.attr(this, 'data-id')) {
                        data_url = data_url + '?id=' + $api.attr(this, 'data-id');
                    }
                }
                var name = "";
                if ($api.attr(this, 'data-name')) {
                    name = $api.attr(this, 'data-name');
                }
                openBrowse(data_url, data_title, share, name);
            });
        }
    }
}

// 判断是否为网址
function isUrl(str_url) { // 验证url
    var strregex = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+)\.)+([A-Za-z0-9-~\/])+$/;
    var re = new RegExp(strregex);
    return re.test(str_url);
}

// 获取Url参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}

// 获取缓存
function getCacheSize(el) {
    api.getCacheSize(function(ret) {
        $api.text(el, parseInt(ret.size / 1024 / 1024) + "MB");;
    });
}

// 用户登录
function login(username, password) {
    api.ajax({
        url: base + 'api/gero/getToken',
        method: 'post',
        headers: {
            'x-requested-with': 'XMLHttpRequest'
        },
        data: {
            values: {
                userName: username,
                password: password
            }
        }
    }, function(ret, err) {
        console.log('ret' + JSON.stringify(ret));
        if (ret && ret.code == 200) {
            $api.setStorage('login', true);
            $api.setStorage('username', username);
            $api.setStorage('password', password);
            $api.setStorage('userinfo', ret);
            var windows = api.windows();
            //   api.alert({
            //     msg:JSON.stringify(windows)
            //   });
            for (var s = 0; s < windows.length; s++) {
                if (windows[s].name !== 'root') {
                    api.closeWin({
                        name: windows[s].name
                    });
                }
            }


            api.openFrame({
                name: 'main',
                url: api.wgtRootDir + '/html/index.html',
                rect: {
                    x: 0,
                    y: 0,
                    w: 'auto',
                    h: 'auto'
                }
            });

        } else if (ret && ret.code == 400) {
            tips('用户名或密码错误', null, 'div');
        } else {
            tips('服务器繁忙，请重新登陆。', null, 'div');
        }
    });
}

// 显示登录
function doLogin() {
    api.openFrame({
        name: 'main',
        url: api.wgtRootDir + '/html/login.html',
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        }
    });
}

// 提示条
function tips(title) {
    var type = arguments[1] ? arguments[1] : 'info';
    var dom = arguments[2] ? arguments[2] : 'body';
    str = '<div class="aui-tips aui-btn-' + type + '" id="tips" tapmode onclick="closeTips()">';
    str += '<i class="aui-iconfont aui-icon-info"></i>';
    str += '<div class="aui-tips-title" id="aui-tips-title">' + title + '</div>';
    str += '<i class="aui-iconfont aui-icon-close" tapmode onclick="closeTips()"></i>';
    str += '</div>';

    if (document.getElementsByClassName("aui-tips").length > 0) {
        $api.html($api.byId('aui-tips-title'), title);
    } else {
        $api.dom(dom).insertAdjacentHTML('afterBegin', str);
    }
}

// 关闭提示条
function closeTips() {
    $api.remove($api.byId("tips"));
}

function base64ToImg(str, callBack) { //传入base64格式的图片，转化为本地图片，返回本地路径
    var arr = str.split(',');
    if (!arr[0] || arr[0].indexOf('base64') === -1) {
        if (!callBack) {
            return str;
        }
        callBack(str);
        return;
    }
    var tmpname = 'imgTmp.' + arr[0].match(/:(.*?);/)[1].split('/')[1];
    var trans = api.require('trans');
    str = arr[1];
    trans.saveImage({
        base64Str: str,
        imgPath: "fs://",
        imgName: tmpname
    }, function(ret, err) {
        if (ret.status) { //若成功，则调用回调函数
            if (!callBack) {
                return "fs://" + tmpname;
            }
            callBack("fs://" + tmpname);
        } else {
            log(err);
        }
    });
}

function openWin(name, url, refresh) {
    var systemType = api.systemType;
    if ('android' === systemType) {
        api.removeEventListener({
            name: 'viewappear'
        });
    }
    if (refresh) {
        if ('android' === systemType) {
            var winName = api.winName;
            var frameName = api.frameName;
            api.addEventListener({
                name: 'viewdisappear'
            }, function(ret, err) {
                api.removeEventListener({
                    name: 'viewdisappear'
                });

                var func = function() {

                    var refresh = '$$$';
                    if (typeof refresh == 'function') {
                        refresh();
                    } else {
                        window.location.reload();
                    }
                };

                var funcArr = func.toString().split("'$$$'");
                refresh = funcArr[0] + refresh + funcArr[1];
                refresh = refresh.replace(/\"/g, "\\\"").replace(/\n/g, "");
                //              log(refresh);
                api.execScript({
                    name: name,
                    script: "api.execScript({name: \"" + winName + "\", frameName: \"" + frameName + "\", script: \"api.addEventListener({name : 'viewappear'}, " + refresh + ");\"});setInterval(function() {api.execScript({name: \"" + winName + "\", frameName: \"" + frameName + "\", script: \"api.addEventListener({name : 'viewappear'}, " + refresh + ");\"});}, 50);"
                });
            });
        } else {
            api.addEventListener({
                name: 'viewappear'
            }, function(ret, err) {
                if (typeof refresh == 'function') {
                    refresh();
                } else {
                    window.location.reload();
                }
                api.removeEventListener({
                    name: 'viewappear'
                });
            });
        }
    }

    var pageParam = {};
    for (var k in api.pageParam) {
        pageParam[k] = api.pageParam[k];
    }

    //	pageParam.historyWin = currentWinName;
    api.openWin({
        name: name,
        url: url,
        animation: {
            type: 'movein', //动画类型（详见动画类型常量）
            subType: 'from_right' //动画子类型（详见动画子类型常量）
        },
        pageParam: pageParam
    });
}
// 图片旋转并获得图片的base64
function rotateBase64Img(src, edg, callback) {

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");

    var imgW; //图片宽度
    var imgH; //图片高度
    var size; //canvas初始大小

    if (edg % 90 != 0) {
        console.error("旋转角度必须是90的倍数!");
        throw '旋转角度必须是90的倍数!';
    }
    (edg < 0) && (edg = (edg % 360) + 360)
    const quadrant = (edg / 90) % 4; //旋转象限
    const cutCoor = {
        sx: 0,
        sy: 0,
        ex: 0,
        ey: 0
    }; //裁剪坐标

    var image = new Image();
    image.crossOrigin = "anonymous"
    image.src = src;

    image.onload = function() {

        imgW = image.width;
        imgH = image.height;
        size = imgW > imgH ? imgW : imgH;

        canvas.width = size * 2;
        canvas.height = size * 2;
        switch (quadrant) {
            case 0:
                cutCoor.sx = size;
                cutCoor.sy = size;
                cutCoor.ex = size + imgW;
                cutCoor.ey = size + imgH;
                break;
            case 1:
                cutCoor.sx = size - imgH;
                cutCoor.sy = size;
                cutCoor.ex = size;
                cutCoor.ey = size + imgW;
                break;
            case 2:
                cutCoor.sx = size - imgW;
                cutCoor.sy = size - imgH;
                cutCoor.ex = size;
                cutCoor.ey = size;
                break;
            case 3:
                cutCoor.sx = size;
                cutCoor.sy = size - imgW;
                cutCoor.ex = size + imgH;
                cutCoor.ey = size + imgW;
                break;
        }


        ctx.translate(size, size);
        ctx.rotate(edg * Math.PI / 180);
        ctx.drawImage(image, 0, 0);

        var imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
        if (quadrant % 2 == 0) {
            canvas.width = imgW;
            canvas.height = imgH;
        } else {
            canvas.width = imgH;
            canvas.height = imgW;
        }
        ctx.putImageData(imgData, 0, 0);
        callback(canvas.toDataURL());
    };
  }
